//***************************************************************************************************************
function Test() {
	// receiveKeywords();
	// receiveReferences();
	// alert("MediaWiki: " + isMediaWikiPageInEditMode().toString());
	collectContent();
}

// ********************************************* G L O B A L O B J E C T S
// *************************************************************

var gui_user_event_handler = new GuiUserEventHandler();

// When addon is loading all addon controls must be invisible becouse there is
// not data to show
window.onload = function() {
	(new GuiHandler).changeHome();
	gui_user_event_handler.initializeGUIOnLoad();
};

// ********************************************* G L O B A L V A R I A B L E S
// *********************************************************
var home_base = "";

var time_interval = 30000; // Collecting content every time_interval

var is_edit = false; // Is currently editing any keyword

var IDClient = "0";
var Discovery = [ {
	priority : "",
	link : [],
	group : ""
} ];

var Keywords = [ {
	priority : "",
	keyword : ""
} ];

// ************************************* G u i U s e r E v e n t H a n d l e r C
// L A S S *********************************************

function GuiUserEventHandler() {
	var gui_handler = new GuiHandler();

	this.initializeGUIOnLoad = function() {
		gui_handler.initializeGUI();
	};

	this.changeViewOnClick = function(view) {
		gui_handler.changeView(view);
	};

	this.openLinkInNewTabOnClick = function(priority) {
		gui_handler.openLinkInNewTab(priority);
	};

	this.imgAddOnClick = function() {
		gui_handler.addKeyword();
	};

	this.imgEditOnClick = function(priority) {
		gui_handler.editKeyword(priority);
	};

	this.imgSaveOnClick = function(priority) {
		gui_handler.saveKeyword(priority);
	};

	this.imgCancelOnClick = function(priority) {
		gui_handler.cancelEditingKeyword(priority);
	};

	this.imgUpOnClick = function(priority) {
		gui_handler.raiseKeywordPriority(priority);
	};

	this.imgDownOnClick = function(priority) {
		gui_handler.reduceKeywordPriority(priority);
	};

	this.imgDeleteOnClick = function(priority) {
		gui_handler.deleteKeyword(priority);
	};

	this.imgHomeBaseOnClick = function() {
		gui_handler.changeHome();
	};
}

// ****************************************************** G u i H a n d l e r C
// L A S S **************************************************

function GuiHandler() {
	var self = this;

	this.getMainWindow = function() {
		return window.QueryInterface(
				Components.interfaces.nsIInterfaceRequestor).getInterface(
				Components.interfaces.nsIWebNavigation).QueryInterface(
				Components.interfaces.nsIDocShellTreeItem).rootTreeItem
				.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
				.getInterface(Components.interfaces.nsIDOMWindow);

	};

	this.getLbPriority = function(priority) {
		return document.getElementById("lbPriority" + priority);
	};

	this.getLbKeyword = function(priority) {
		return document.getElementById("lbKeyword" + priority);
	};

	this.getTbKeyword = function(priority) {
		return document.getElementById("tbKeyword" + priority);
	};

	this.getImgUp = function(priority) {
		return document.getElementById("imgUp" + priority);
	};

	this.getImgDown = function(priority) {
		return document.getElementById("imgDown" + priority);
	};

	this.getImgEdit = function(priority) {
		return document.getElementById("imgEdit" + priority);
	};

	this.getImgDelete = function(priority) {
		return document.getElementById("imgDelete" + priority);
	};

	this.getImgSave = function(priority) {
		return document.getElementById("imgSave" + priority);
	};

	this.getImgCancel = function(priority) {
		return document.getElementById("imgCancel" + priority);
	};

	this.getLbGroupPriority = function(priority) {
		return document.getElementById("lbGroupPriority" + priority);
	};
	this.getLbGroupLink = function(priority) {
		return document.getElementById("lbGroupLink" + priority);
	};
	this.getLbNoOfG = function(priority) {
		return document.getElementById("lbNoOfG" + priority);
	};
	this.initializeGUI = function() {
		initializeRelevantLinkGUI();
		initializeKeywordGUI();
		this.changeHome();
		collectContent();

	};

	function initializeRelevantLinkGUI() {
		var labels = document.getElementsByTagName("label");
		for ( var i = 0; i < labels.length; i++)
			if (labels[i].className == "labelsLink")
				labels[i].style.visibility = "hidden";
	}

	function initializeKeywordGUI() {
		var labels = document.getElementsByTagName("label");
		for ( var i = 0; i < labels.length; i++)
			if (labels[i].className == "labelsPriority"
					|| labels[i].className == "labelsKeyword")
				labels[i].style.visibility = "hidden";

		var images = document.getElementsByTagName("image");
		for ( var i = 0; i < images.length; i++)
			if (images[i].className == "imgUp"
					|| images[i].className == "imgDown"
					|| images[i].className == "imgEdit"
					|| images[i].className == "imgDelete")
				images[i].style.visibility = "hidden";
	}

	this.changeView = function(view) {
		if (view == 0) {
			document.getElementById("dckMain").selectedIndex = 0;
			document.getElementById("dckKeywordPanel").selectedIndex = 1;
			document.getElementById("dckHomePanel").selectedIndex = 1;
		} else if (view == 1) {
			document.getElementById("dckMain").selectedIndex = 0;
			document.getElementById("dckKeywordPanel").selectedIndex = 0;
			document.getElementById("dckHomePanel").selectedIndex = 0;
		} else
			throw new Error(
					"Undefined view parametar in function changeView(view) in class GuiHandler!");
	};

	// ----------------------------------- Links
	// ---------------------------------------------------
	this.showSearch = function() {
		if (Discovery != null && Discovery.length > 0 && Discovery.length <= 9) {
			for ( var i = 0; i < Discovery.length; i++) {
				this.getLbGroupPriority(i + 1).style.visibility = "visible";
				this.getLbGroupPriority(i + 1).value = Discovery[i].priority;
				this.getLbGroupLink(i + 1).style.visibility = "visible";
				this.getLbGroupLink(i + 1).value = Discovery[i].group;
				this.getLbNoOfG(i + 1).style.visibility = "visible";
				this.getLbNoOfG(i + 1).value = Discovery[i].link.length;
			}
		}
	};

	this.openLinkInNewTab = function(priority) {
		this.getMainWindow().gBrowser
				.addTab("localhost:8000/grouplinks/"+IDClient+"/"+Discovery[priority-1].group);
	};

	// --------------------------- Keywords
	// -------------------------------------------

	this.showKeywords = function() {
		if (Keywords != null && Keywords.length > 0 && Keywords.length <= 8) {
			for ( var i = 0; i < Keywords.length; i++) {
				if (i == 0)
					setControlVisibility(new Array(this.getLbPriority(i + 1),
							this.getLbKeyword(i + 1), this.getImgEdit(i + 1),
							this.getImgDelete(i + 1), this.getImgDown(i + 1)),
							"visible");
				else if (i == 7 || i + 1 == Keywords.length)
					setControlVisibility(new Array(this.getLbPriority(i + 1),
							this.getLbKeyword(i + 1), this.getImgEdit(i + 1),
							this.getImgDelete(i + 1), this.getImgUp(i + 1)),
							"visible");
				else
					setControlVisibility(new Array(this.getLbPriority(i + 1),
							this.getLbKeyword(i + 1), this.getImgEdit(i + 1),
							this.getImgDelete(i + 1), this.getImgUp(i + 1),
							this.getImgDown(i + 1)), "visible");

				this.getLbKeyword(i + 1).value = Keywords[i].keyword.trim();
				this.getLbKeyword(i + 1).setAttribute("tooltiptext",
						Keywords[i].keyword.trim());
			}
		}
	};

	this.addKeyword = function() {
		if (is_edit) {
			var txt = "You are already editing keyword!\n";
			txt += "You must finish keyword editing to add new keyword!";
			txt += "Click OK to continue!\n";
			alert(txt);
			return;
		}

		var new_priority = document.getElementById("mlPriorityAdd").selectedItem.value;
		var new_keyword = this.getTbKeyword("Add").value.trim();

		if (new_keyword == "") {
			alert("You didn't enter keyword!\nClick OK to continue!");
			this.getTbKeyword("Add").value = "";
			return;
		}

		var keyword_manager = new KeywordManager();
		keyword_manager.addNewKeyword(new_priority, new_keyword);
		displayNewKeyword(parseInt(new_priority, 10), new_keyword);
	};

	function displayNewKeyword(new_priority, new_keyword) {
		if (new_priority == 8
				&& self.getLbPriority("8").style.visibility == "visible") {
			self.getLbKeyword("8").value = new_keyword;
			self.getLbKeyword("8").setAttribute("tooltiptext", new_keyword);
			return;
		}

		if (self.getLbPriority(new_priority).style.visibility == "hidden") {
			if (new_priority == 1) {
				self.getLbKeyword("1").value = new_keyword;
				self.getLbKeyword("1").setAttribute("tooltiptext", new_keyword);
				setControlVisibility(new Array(self.getLbPriority("1"), self
						.getLbKeyword("1"), self.getImgDown("1"), self
						.getImgEdit("1"), self.getImgDelete("1")), "visible");
			} else if (self.getLbPriority(new_priority - 1).style.visibility == "visible") {
				self.getLbKeyword(new_priority).value = new_keyword;
				self.getLbKeyword(new_priority).setAttribute("tooltiptext",
						new_keyword);
				if (new_priority != 8) {
					setControlVisibility(new Array(self
							.getLbPriority(new_priority), self
							.getLbKeyword(new_priority), self
							.getImgUp(new_priority), self
							.getImgDown(new_priority), self
							.getImgEdit(new_priority), self
							.getImgDelete(new_priority), self
							.getImgDown(new_priority - 1)), "visible");
					self.getImgDown(new_priority).style.visibility = "hidden";
				} else {
					setControlVisibility(new Array(self.getLbPriority("8"),
							self.getLbKeyword("8"), self.getImgUp("8"), self
									.getImgEdit("8"), self.getImgDelete("8"),
							self.getImgDown("7")), "visible");
				}
			} else {
				displayNewKeyword(new_priority - 1, new_keyword);
			}
			return;
		}
		if (self.getLbPriority(new_priority).style.visibility == "visible") {
			var tmpKeyword = self.getLbKeyword(new_priority).value;
			self.getLbKeyword(new_priority).value = new_keyword;
			self.getLbKeyword(new_priority).setAttribute("tooltiptext",
					new_keyword);
			displayNewKeyword(new_priority + 1, tmpKeyword);
		}
	}

	this.editKeyword = function(priority) {
		if (is_edit) {
			var txt = "You are already editing keyword!\n";
			txt += "You must finish keyword editing to edit another keyword!";
			txt += "Click OK to continue!\n";
			alert(txt);
			return;
		}

		is_edit = true;
		setAppropriateKeywordControls(priority, true);
		showAppropriateKeywordControls(priority, "1");
	};

	this.saveKeyword = function(priority) {
		var old_keyword = this.getLbKeyword(priority).value.trim();
		var new_keyword = this.getTbKeyword(priority).value.trim();

		if (new_keyword == "") {
			alert("You didn't enter keyword!\nClick OK to continue!");
			return;
		}

		if (old_keyword != new_keyword) {
			var keyword_manager = new KeywordManager();
			keyword_manager.editKeyword(old_keyword, priority, new_keyword);
		}

		setAppropriateKeywordControls(priority, false);
		showAppropriateKeywordControls(priority, "0");
		is_edit = false;
	};

	this.cancelEditingKeyword = function(priority) {
		this.getTbKeyword(priority).value = "";
		showAppropriateKeywordControls(priority, "0");
		is_edit = false;
	};

	function setAppropriateKeywordControls(priority, in_edit_mode) {
		if (in_edit_mode) {
			self.getTbKeyword(priority).value = self.getLbKeyword(priority).value;
		} else {
			self.getLbKeyword(priority).value = self.getTbKeyword(priority).value;
			self.getLbKeyword(priority).setAttribute("tooltiptext",
					self.getTbKeyword(priority).value);
			self.getTbKeyword(priority).value = "";
		}
	}

	function showAppropriateKeywordControls(priority, selected_index) {
		var row = document.getElementById("rwKeyword" + priority);
		var deck = row.getElementsByTagName("deck");
		for ( var i = 0; i < deck.length; i++)
			deck[i].setAttribute("selectedIndex", selected_index);
	}

	this.deleteKeyword = function(priority) {
		if (is_edit) {
			var txt = "You are already editing keyword!\n";
			txt += "You must finish keyword editing to delete keyword!";
			alert(txt);
			return;
		}

		var keyword_manager = new KeywordManager();
		keyword_manager.deleteKeyword(this.getLbKeyword(priority).value);
		reorderKeywordsOnDelete(parseInt(priority, 10));
	};

	function reorderKeywordsOnDelete(priority) {
		if (priority == 8
				|| self.getLbKeyword(parseInt(priority, 10) + 1).style.visibility == "hidden") {
			self.getLbKeyword(priority).value = "";
			self.getLbKeyword(priority).removeAttribute("tooltiptext");
			if (priority == 1) {
				setControlVisibility(new Array(self.getLbPriority("1"), self
						.getLbKeyword("1"), self.getImgDown("1"), self
						.getImgEdit("1"), self.getImgDelete("1")), "hidden");
			} else if (priority == 8) {
				setControlVisibility(new Array(self.getLbPriority("8"), self
						.getLbKeyword("8"), self.getImgUp("8"), self
						.getImgEdit("8"), self.getImgDelete("8"), self
						.getImgDown("7")), "hidden");
			} else {
				setControlVisibility(new Array(self.getLbPriority(priority),
						self.getLbKeyword(priority), self.getImgUp(priority),
						self.getImgDown(priority), self.getImgEdit(priority),
						self.getImgDelete(priority)), "hidden");
				self.getImgDown(priority - 1).style.visibility = "hidden";
			}
		} else {
			self.getLbKeyword(priority).value = self.getLbKeyword(parseInt(
					priority, 10) + 1).value;
			self.getLbKeyword(priority).setAttribute("tooltiptext",
					self.getLbKeyword(parseInt(priority, 10) + 1).value);
			reorderKeywordsOnDelete(parseInt(priority, 10) + 1);
		}
	}

	function setControlVisibility(controls, visibility) {
		for ( var i = 0; i < controls.length; i++)
			controls[i].style.visibility = visibility;
	}

	this.raiseKeywordPriority = function(priority) {
		if (is_edit) {
			var txt = "You are already editing keyword!\n";
			txt += "You must finish keyword editing to reorder keywords!";
			alert(txt);
			return;
		}

		var edited_keyword = this.getLbKeyword(priority).value.trim();
		var keyword_manager = new KeywordManager();
		keyword_manager.editKeyword(edited_keyword, priority - 1,
				edited_keyword);

		this.getLbKeyword(priority).value = this.getLbKeyword(priority - 1).value
				.trim();
		this.getLbKeyword(priority - 1).value = edited_keyword;
	};

	this.reduceKeywordPriority = function(priority) {
		if (is_edit) {
			var txt = "You are already editing keyword!\n";
			txt += "You must finish keyword editing to reorder keywords!";
			alert(txt);
			return;
		}

		var edited_keyword = this.getLbKeyword(priority).value.trim();
		var keyword_manager = new KeywordManager();
		keyword_manager.editKeyword(edited_keyword, parseInt(priority, 10) + 1,
				edited_keyword);

		this.getLbKeyword(priority).value = this.getLbKeyword(parseInt(
				priority, 10) + 1).value.trim();
		this.getLbKeyword(parseInt(priority, 10) + 1).value = edited_keyword;
	};

	// ----------------------------- Settings ---------------------------

	this.changeHome = function() {
		home_base = this.getMainWindow().content.location.href;
	};

}

// ************************* C o n t e n t M a n a g e r C L A S S
// ****************

function ContentManager() {
	function Content(content) {
		this.id = IDClient;
		this.content = content;
	}

	this.sendContent = function(content) {
		var ajax_worker = new AJAXWorker();
		var message = objectToJson(new Content(content));
		ajax_worker.sendContentRequest(message);
	};
}

var _gui = new GuiHandler();


function collectContent() {
	var content = "";
	if (home_base == _gui.getMainWindow().content.location.href) {
		if (isMediaWikiPageInEditMode()) {
			var win = _gui.getMainWindow().content;
			var _mediawiki_content = new MediaWikiContentCollector();
			content = _mediawiki_content.collectContentMediawiki(win);
			content = _mediawiki_content.cleanWikiContent(content);
		} else {
			var _generic_content = new GenericContentCollector();		
			content = _generic_content.collectGenericContent(_gui
					.getMainWindow().content.document);
		}
	}
	//alert(content);
	var content_manager = new ContentManager();
	content_manager.sendContent(content);
	setTimeout("collectContent();", time_interval);
}

// ************************G e n e r i c C o n t e n t C o l l e c t o r C L A S
// S **********
function GenericContentCollector() {

	this.collectGenericContent = function(doc) {
		var SPLITER = "  ";
		var collected_text = "";

		textareas = doc.getElementsByTagName('textarea');
		for ( var i = 0; i < textareas.length; i++) {
			if (textareas[i].value != '') {
				collected_text = collected_text + textareas[i].value;
				collected_text = collected_text + SPLITER;
			}
		}
		return collected_text;
	};
}
